'use strict'

let ws = require('ws').Server
let sceneMgr = require('./sceneMgr')
let remoteCall = require('./remoteCall')
let routes  = require('./route')


//会话类(子节点连接类)
class Node {
  constructor(nId, socket) {
    this.id = nId
    this.name = ''
    this.socket = socket
    this.reqId = 0
    let self = this
    this.callbacks = {}

    socket.on('message', function(data) {
      data = JSON.parse(data)
      let reqId = data.reqId
      if (reqId && self.callbacks[reqId]) {
        self.callbacks[reqId](data.msg)
        delete self.callbacks[reqId]
      } else {
        let remoteFunc = remoteCall.getCall(data.route)
        remoteFunc(self, data.msg)
      }
    })

    socket.on('close', function(data) {
      console.log(self.name + '子节点连接关闭')
      nodeMgr.delNodeBycId(self.id)
    })

    socket.on('error', function(data) {
      this.emit('close')
    })
  }

  //发送消息给子节点
  send(pId, route, msg, cb) {
    this.reqId += 1
    let data = {
      reqId: this.reqId,
      route: route,
      pId: pId,
      msg: msg
    }
    this.callbacks[this.reqId] = cb
    let sendData = JSON.stringify(data)
    this.socket.send(sendData)
  }

  close() {
    this.socket.close()
  }
}

//会话管理类(用子节点连接管理类)
class NodeMgr {
  constructor() {
    this.nodes = {} //保存socket.id对应的node
    this.nodesName = {} //保存nodeName对应的node
  }

  createNode(nId, socket) {
    var node = new Node(nId, socket)
    this.nodes[nId] = node
    return node
  }

  get(nId) {
    return this.nodes[nId]
  }

  getBynodeName(name) {
    return this.nodesName[name]
  }

  bind(nId, name) {
    Log(name + '子节点注册')
    let node = this.nodes[nId]
    node.name = name
    this.nodesName[name] = node
  }

  delnode(node) {
    delete this.nodes[node.id]
    delete this.nodesName[node.name]
  }

  delNodeBycId(nId) {
    let node = this.nodes[nId]
    delete this.nodes[nId]
    delete this.nodesName[node.name]
  }
}

let nodeMgr = new NodeMgr()
module.exports = nodeMgr
